/*
 * @lc app=leetcode.cn id=811 lang=typescript
 *
 * [811] 子域名访问计数
 */

// @lc code=start
function subdomainVisits(cpdomains: string[]): string[] {
  const counts = new Map<string, number>();
  // 记录每个域名的出现次数
  for (const x of cpdomains) {
    let [count, domain] = x.split(' ');
    counts.set(domain, (counts.get(domain) || 0) + Number(count));
    const n = domain.length;
    // 记录每个子域名的出现次数
    for (let i = 0; i < n; i++) {
      if (domain[i] === '.') {
        const subdomain = domain.substring(i + 1);
        counts.set(subdomain, (counts.get(subdomain) || 0) + Number(count));
      }
    }
  }

  const ans: string[] = [];
  for (const [subdomain, count] of counts.entries()) {
    ans.push(`${count} ${subdomain}`);
  }

  return ans;
}
// @lc code=end
